package cn.rengy.isql;

import cn.rengy.auth.UserService;
import cn.rengy.auth.entity.principal.Identity;
import cn.rengy.isql.entity.SqlRole;
import cn.rengy.util.web.RequestUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.security.Principal;
import java.util.List;


@Slf4j
@DS("admin")
public class GetSqlService {

    private DbSqlValueService dbSqlValueService;

    private SqlRoleService sqlRoleService;

    private UserService userService;

    public GetSqlService(UserService userService,SqlRoleService sqlRoleService,DbSqlValueService dbSqlValueService) {
        this.userService=userService;
        this.dbSqlValueService = dbSqlValueService;
        this.sqlRoleService=sqlRoleService;
    }


    public SqlEntity getSqlEntityByName(String sqlname){
        SqlEntity sqlEntity=  dbSqlValueService.getSqlEntityByName(sqlname);
        String authCode=sqlEntity.getAuthCode();
        if(StringUtils.hasLength(authCode)){
            boolean match=false;
            //查询当前角色
            Identity identity=(Identity)RequestUtil.getPrincipal();
            if(identity!=null){
                Long userId=identity.getUserId();
                List<String> roles=userService.getRoles(userId);
                if(roles!=null){
                    //查询当前角色对应的sql
                    List<SqlRole> sqlRoleList= sqlRoleService.getSqlRole(authCode);
                    if(sqlRoleList!=null){
                        for(SqlRole sqlRole:sqlRoleList){
                            if(roles.contains(sqlRole.getRoleCode())){
                                match=true;
                                log.info("用户[{}]拥有角色[{}],执行对应sql[{}]",userId,sqlRole.getRoleCode(),sqlRole.getSqlName());
                                sqlEntity=  dbSqlValueService.getSqlEntityByName(sqlRole.getSqlName());
                                break;
                            }
                        }
                    }
                }
                if(!match){
                    log.warn("用户[{}]没有匹配的角色权限SQL",userId);
                }
            }else{
                log.warn("用户未认证");
            }
        }
        return sqlEntity;
    }
}
